#include "thread_pool.h"

ThreadPool& ThreadPool::getInstance(int numThreads)
{
    static ThreadPool instance(numThreads);
    return instance;
}

ThreadPool::ThreadPool(int numThreads) : stop(false)
{
    for (int i = 0; i < numThreads; ++i)
    {
        workers.emplace_back([this]
            { worker(); });
    }
}

ThreadPool::~ThreadPool()
{
    stop.store(true);
    condition.notify_all();
    for (std::thread& worker : workers)
    {
        worker.join();
    }
}

void ThreadPool::worker()
{
    while (true)
    {
        std::function<void()> task;
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            condition.wait(lock, [this]
                { return stop.load() || !tasks.empty(); });
            if (stop.load() && tasks.empty())
            {
                return;
            }
            task = std::move(tasks.front());
            tasks.pop();
        }
        task();
    }
}

void ThreadPool::addTask(std::function<void()> task)
{
    {
        std::unique_lock<std::mutex> lock(queueMutex);
        if (stop.load())
        {
            throw std::runtime_error("ThreadPool is stopping, cannot enqueue new tasks.");
        }
        tasks.emplace(task);
    }
    condition.notify_one();
}
